package com.yangyang.notepad;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.util.LinkedList;

public class UndoRedoHelper {
    private EditText editText;
    private LinkedList<String> history = new LinkedList<>();
    private LinkedList<String> redoHistory = new LinkedList<>();
    private int maxHistorySize = 100;
    private int currentPosition = -1;

    public UndoRedoHelper(EditText editText) {
        this.editText = editText;
        saveState();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                saveState();
            }
        });
    }

    private void saveState() {
        String currentText = editText.getText().toString();
        // 如果与上次记录相同则不保存
        if (history.isEmpty() || !history.getLast().equals(currentText)) {
            history.add(currentText);
            redoHistory.clear();

            // 限制历史记录大小
            if (history.size() > maxHistorySize) {
                history.removeFirst();
            }

            currentPosition = history.size() - 1;
        }
    }

    public void undo() {
        if (canUndo()) {
            redoHistory.add(history.removeLast());
            currentPosition--;
            editText.setText(history.getLast());
            editText.setSelection(editText.getText().length());
        }
    }

    public void redo() {
        if (canRedo()) {
            String text = redoHistory.removeLast();
            history.add(text);
            currentPosition++;
            editText.setText(text);
            editText.setSelection(editText.getText().length());
        }
    }

    public boolean canUndo() {
        return history.size() > 1;
    }

    public boolean canRedo() {
        return !redoHistory.isEmpty();
    }
}